import holidays
from lunarcalendar import Converter, Solar, Lunar
from datetime import datetime, timedelta
from flask import request


# 根据年份获取节假日
def holidaylist(year):
    # 根据holidays组件获取法定节假日
    data = []
    cn_holidays = holidays.country_holidays('CN', None, year)
    for date, name in sorted(cn_holidays.items()):
        data.append(str(date))
    return data


# 格式化后的节日数据 (统一为元组格式)
gregorian_festival_data = {
    (1, 1): "元旦节",
    (3, 8): "妇女节",
    (3, 12): "植树节",
    (4, 4): "清明节",
    (5, 1): "劳动节",
    (5, 4): "青年节",
    (6, 1): "儿童节",
    (7, 1): "建党节",
    (8, 1): "建军节",
    (9, 10): "教师节",
    (10, 1): "国庆节",
}


# 获取公历节日
def get_gregorian_festival(solar_date):
    # 如果输入是字符串，转换为日期
    if isinstance(solar_date, str):
        from datetime import datetime
        solar_date = datetime.strptime(solar_date, "%Y-%m-%d").date()
    # 提取月份和日期组成键
    key = (solar_date.month, solar_date.day)
    return gregorian_festival_data.get(key)


# 农历节日表
lunar_festivals = {
    (1, 1): "春节",
    (1, 15): "元宵节",
    (5, 5): "端午节",
    (7, 7): "七夕节",
    (7, 15): "中元节",
    (8, 15): "中秋节",
    (9, 9): "重阳节",
    (12, 8): "腊八节",
    (12, 23): "北方小年",
    (12, 24): "南方小年",
}


# 获取农历节假日
def get_lunar_festival(solar_date):
    lunar = Converter.Solar2Lunar(solar_date)
    festival = lunar_festivals.get((lunar.month, lunar.day))
    # 除夕特殊判断
    if festival is None and lunar.month == 12:
        solar_date_plus = solar_date + timedelta(days=1)
        next_solar = Solar(solar_date_plus.year, solar_date_plus.month, solar_date_plus.day)
        next_lunar = Converter.Solar2Lunar(next_solar)
        if next_lunar.month == 1 and next_lunar.day == 1:
            return "除夕"
    else:
        return festival


# 获取传参的年份
def get_year():
    # 默认当前年份
    year = datetime.today().year
    if request.method == "POST":
        year = int(request.form.get("year"))
    elif request.method == "GET":
        year = int(request.args.get("year"))
    return year


# 获取月份
def get_month():
    return datetime.today().month
